<template>
  <div class="clearfix">
    <a-upload
        v-model:file-list="fileList"
        :action="uploadPath"
        multiple
        list-type="picture-card"
        @preview="handlePreview"
        @change="handleChange"
    >
      <div v-if="fileList.length < 8">
        <plus-outlined />
        <div style="margin-top: 8px">Upload</div>
      </div>
    </a-upload>
    {{previewImage}}
    <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script  setup>
import {getBaseURL} from "@/config/common.js";

const uploadPath = ref(getBaseURL() +"/minio/upload")
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const fileList = ref([{
  uid: '-1',
  name: 'image.png',
  status: 'done',
  url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
}]);

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
const handleBeforeUpload = ()=>{
  return true;
}
const handlePreview = async (file) => {
  if (!file.response.data && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.response.data || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.response.data.substring(file.response.data.lastIndexOf('/') + 1);
};

const handleChange = (info) => {
  if (info.file.status === 'uploading') {
    return;
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.
    // getBase64(info.file.originFileObj, (base64Url: string) => {
    //   imageUrl.value = base64Url;
    //   loading.value = false;
    // });
    message.success('upload success!');
  }
  if (info.file.status === 'error') {
    message.error('upload error');
  }
}
</script>
<style scoped>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
